<template>
  <el-table :data="tableData" v-loading="loading" row-key="id" style="width: 100%">
    <el-table-column prop="alertLevel" label="告警等级" width="90" align="center" />
    <el-table-column prop="alertCondition" label="触发条件" width="200" header-align="center" />
    <el-table-column prop="alertValue" label="告警实际值" width="100" align="center" />
    <el-table-column prop="alertThreshold" label="告警等级触发阈值" width="100" align="center" />
    <el-table-column prop="warningFlowList" label="告警流水" header-align="center">
      <template #default="{ row }">
        <div v-if="!row.isChild">
          共{{ Object.keys(row.warningFlowList).length }}类记录
        </div>
        <div v-else v-html="row.warningFlowList"></div>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup>
import { ref, watch } from 'vue'
import { selectCustomerAlertDetailAPI } from '@/api'

const props = defineProps({
  alertId: {
    type: Number,
    default: null
  }
})

const tableData = ref([])
const loading = ref(false)

// 格式化子节点数据
const formatterChildren = (parent) => {
  const children = []
  
  for (const [key, records] of Object.entries(parent.warningFlowList)) {
    let html = `<strong>${key}</strong>：<br/>`
    records.forEach(record => {
      html += `&emsp;&emsp;${record}<br/>`
    })
    
    children.push({
      id: `${parent.id}-${key}`,  // 确保唯一ID
      warningFlowList: html,
      isChild: true  // 标记为子节点
    })
  }
  
  return children
}

// 获取数据
const getList = async () => {
  loading.value = true
  try {
    const { data } = await selectCustomerAlertDetailAPI({ alertId: props.alertId })
    tableData.value = data.map(item => {
      return {
        ...item,
        children: formatterChildren(item)
      }
    })
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

watch(() => props.alertId, (newVal) => {
  if (newVal) {
    getList()
  } else {
    tableData.value = []
  }
}, { immediate: true })
</script>

<style lang="less" scoped>
:deep(.el-table .cell) {
  white-space: pre-wrap;
  // max-height: 70px;
  overflow: auto;
}

/* 树形表格子节点缩进 */
:deep(.el-table__row--level-1) td:first-child .cell {
  padding-left: 40px !important;
}

/* 为弹框内容添加滚动条 */
:deep(.el-dialog__body) {
  max-height: 60vh;
  overflow-y: auto;
}

:deep(.el-divider--horizontal) {
  margin: 12px 0;
}
</style>